#include <stdio.h>
#include <math.h>

//函数：x^3 − x − 1 
double f1(double x)
{
	return pow(x,3) - x -1;
}
//函数：x^3 − x − 1的导数
double h1(double x)
{
	return 3 * pow(x,2) - 1;
}
//函数：−x^3 + 5x
double f2(double x)
{
	return -pow(x,3) +5*x;
}
//函数：−x^3 + 5x的导数
double h2(double x)
{
	return -3 * pow(x,2) + 5;
}
//阻尼
double damp(double x,int i)
{
	return x * pow(2,-i);
}
//函数指针参数分别为函数和导数
double Newton(double x,double w,double (*f)(double),double (*h)(double))
{
	int k = 0;
	int i = 0;
	double y = x;	//x[k+1]
	double s;
	double min = 0.000001;	//误差阀值
	while(fabs(f(x)) > min)
	{
		s = f(x)/h(x);
		y = x - s;
		i = 0;
		while(fabs(f(y)) >= fabs(f(x)))
		{
			y = x - damp(w,i)*s;
			i++;
		}
		printf("迭代%d：\n  阻尼因子：%f \n  近似解：%f\n",k,damp(w,i),x);		
		k++;
		x = y;
	}
	return y;	
}

int main()
{
	printf("x^3 − x − 1 = 0\n");
	Newton(0.6,1,f1,h1);
	printf("\n−x^3 + 5x = 0\n");	
	Newton(1.2,1,f2,h2);
	return 0;
}
